"""
@release: fsray-api-alpha
@file: record.py
@author: lingdubing
@desc: 操作订单行为的接口层
@character: utf-8
"""

from datetime import datetime, timedelta
from collections import Counter
from fastapi import APIRouter, Depends, Header
from models.models import Machine, Area, Record, User
from schemas.response import *
import jwt
from core.Auth import check_permission, verify_token
from config import settings
from schemas.record_schemas import RecordPaingtionModel
from service.RecordService import RecordService
from service.UserService import UserService
from service.AreaService import AreaService
from service.MachineService import MachineService

router = APIRouter()

@router.post("/get_record_list", summary="获取订单列表", response_model=ReturnDataModel, dependencies=[Depends(check_permission)])
async def get_record_list(query: RecordPaingtionModel, user_info: tuple = Depends(check_permission)):
    """
    获取订单列表
    :param query:
    :param user_info:
    :return:
    """

    record_service = RecordService()
    user_service = UserService()

    # 获取当前时间
    current_time = datetime.now()
    start_time = None
    user_id, role_id = user_info

    # 计算时间筛选的开始时间
    if query.time_range == '3d':
        start_time = current_time - timedelta(days=3)
    elif query.time_range == '1w':
        start_time = current_time - timedelta(weeks=1)
    elif query.time_range == '1m':
        start_time = current_time - timedelta(days=30)

    record_list, total = record_service.get_record_list(page=query.page, page_size=query.page_size,
                                                        start_time=start_time, record_id=query.record_id,
                                                        user_id = user_id, role_id=role_id)

    final_list = []
    record_service.close()
    for record in record_list:
        final_list.append({
            "create_time": record.create_time,
            "update_time": record.update_time,
            "record_id": record.record_id,
            "start_time": record.start_time,
            "end_time": record.end_time,
            "stop_time": record.stop_time,
            "consume_battery": record.consume_battery,
            "username": user_service.get_user_by_id(record.user_id).username,
            "tracejectory": record.tracejectory,
            "machine_id": record.machine_id
        })

    return ReturnDataModel(data=final_list, total=total, code=STATUS_CODE["success"], message="获取订单列表成功", success=True)

@router.get('/get_anaylze', summary="获取统计信息", response_model=ReturnDataModel, dependencies=[Depends(check_permission)])
async def get_anaylze():
    """
    获取统计信息
    :return:
    """
    user_service = UserService()
    record_service = RecordService()
    machine_service = MachineService()
    area_service = AreaService()

    anaylze_result = {}

    # 获取当前日期和本周一的日期
    today = datetime.today()
    start_of_week = today - timedelta(days=today.weekday())  # 本周一的日期
    start_of_last_week = today - timedelta(days=today.weekday() + 7)  # 上周一的日期
    end_of_last_week = start_of_last_week + timedelta(days=6)  # 上周日的日期

    # 获取系统的所有人数
    anaylze_result["user_count"] = len(user_service.get_all())
    # 获取系统的所有电动车数
    anaylze_result["machine_count"] = len(machine_service.get_all())
    # 获取系统正在骑行的电动车
    anaylze_result["riding_machine_count"] = len(machine_service.get_machine_list(page=1,page_size=500, status=0)[0])
    # 获取系统违规停放的电动车
    anaylze_result["illegal_machine_count"] = len((machine_service.get_machine_list(page=1,page_size=500, status=2))[0])
    # 获取系统所有区域
    anaylze_result["all_area_count"] = len(area_service.get_all())
    # 获取本周的订单数，按星期几分开
    anaylze_result["week_order_count"] = []
    for i in range(7):  # 遍历从本周一到本周日
        # 当前星期几的日期
        day_of_week = start_of_week + timedelta(days=i)

        # 获取当天的开始时间和结束时间
        day_start = datetime.combine(day_of_week, datetime.min.time())  # 当天的零点
        day_end = datetime.combine(day_of_week, datetime.max.time())  # 当天的最后一刻

        # 查询当天的订单数
        order_count = len(
            record_service.get_record_list(start_time=day_start, end_time=day_end, page=1, page_size=500)[0]
        )
        anaylze_result["week_order_count"].append(order_count)

    # 获取上周的订单数，按星期几分开
    anaylze_result["week_order_count_last_week"] = []
    for i in range(7):  # 上周
        day_of_week = start_of_last_week + timedelta(days=i)
        day_start = datetime.combine(day_of_week, datetime.min.time())
        day_end = datetime.combine(day_of_week, datetime.max.time())
        order_count = len(
            record_service.get_record_list(start_time=day_start, end_time=day_end, page=1, page_size=500)[0]
        )
        anaylze_result["week_order_count_last_week"].append(order_count)

    # 获取上周的被骑行次数前十的电动车编号和次数
    records = record_service.get_record_list(start_time=start_of_week, end_time=start_of_last_week, page=1, page_size=500)[0]
    machine_ride_counts = Counter(record.machine_id for record in records)  # 统计电动车的骑行次数
    top_10_machines = machine_ride_counts.most_common(10)  # 获取前十的电动车编号和骑行次数
    anaylze_result["top_10_machines"] = top_10_machines

    # 获取上周的骑行次数前十的用户编号和次数
    user_ride_counts = Counter(record.user_id for record in records)  # 统计用户的骑行次数
    top_10_users = user_ride_counts.most_common(10)  # 获取前十的用户编号和骑行次数
    anaylze_result["top_10_users"] = top_10_users

    return ReturnDataModel(
        code=STATUS_CODE["success"],
        message="获取统计信息成功",
        data=[anaylze_result],
        success=True,
        total=0
    )











